package com.hj.response.resp;

import com.alibaba.fastjson2.JSON;
import com.hj.response.annotation.IgnoreResponse;
import com.hj.response.constant.RespConstant;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.LinkedHashMap;
import java.util.Objects;

/**
 * @author hj
 * @Date 2023/4/26
 * @Description: 全局统一返回处理
 */
@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //检查是否有 @IgnoreResponseAdvice 注解  有则忽略拦截
        //判断类上有没有注解
        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponse.class)) {
            return false;
        }
        //判断 方法上有没有注解
        if (Objects.requireNonNull(methodParameter.getMethod()).isAnnotationPresent(IgnoreResponse.class)) {
            return false;
        }
        //判断请求路径
        if (methodParameter.getDeclaringClass().getName().contains(RespConstant.SPRINGDOC)) {
            return false;
        }
        if (methodParameter.getDeclaringClass().getName().contains(RespConstant.V3)) {
            return false;
        }
        return true;
    }

    @Override
    @SuppressWarnings("all")
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        RestfulResult<Object> resp = new RestfulResult<>();
        if (o instanceof RestfulResult) {
            return o;
        }
        resp.setCode(RespConstant.SUCCESS_CODE);
        resp.setMsg(RespConstant.SUCCESS);
        resp.setData(o);
        if (o instanceof String) {
            return JSON.toJSONString(resp);
        }
        if (o instanceof LinkedHashMap) {
            LinkedHashMap map = (LinkedHashMap) o;
            resp.setMsg(map.get("message").toString());
            resp.setData(map.get("message").toString());
            resp.setCode(Integer.parseInt(map.get("code").toString()));
            return resp;
        }
        return resp;
    }


}
